package com.egg.ylt.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.egg.ylt.R;
import com.egg.ylt.Utils.CustomUtils;
import com.egg.ylt.Utils.StatusBarUtil;
import com.egg.ylt.Utils.StringUtil;
import com.egg.ylt.pojo.AppointmentServeListEntity;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.yonyou.framework.library.base.BaseActivity;
import com.yonyou.framework.library.bean.ErrorBean;

import butterknife.BindView;
import butterknife.OnClick;

public class ACT_OrderDetail extends BaseActivity {

    @BindView(R.id.order_status_iv)
    ImageView mOrderStatusIv;
    @BindView(R.id.order_status_tv)
    TextView mOrderStatusTv;
    @BindView(R.id.order_description_tv)
    TextView mOrderDescriptionTv;

    @BindView(R.id.store_name_tv)
    TextView mStoreNameTv;

    @BindView(R.id.store_address_tv)
    TextView mStoreAddressTv;

    @BindView(R.id.store_phone_iv)
    ImageView mStorePhoneIv;

    @BindView(R.id.order_time_tv)
    TextView mOrderTimeTv;

    @BindView(R.id.service_name_tv)
    TextView mServiceNameTv;

    @BindView(R.id.technician_tv)
    TextView mTechnicianNameTv;

    @BindView(R.id.order_number_tv)
    TextView mOrderNumberTv;
    @BindView(R.id.phone_number_tv)
    TextView mPhoneNumberTv;
    @BindView(R.id.order_create_time_tv)
    TextView mOrderCreateTimeTv;

    @BindView(R.id.qr_code_ll)
    LinearLayout mQrCodeLl;

    @BindView(R.id.qr_code_iv)
    ImageView mQrCodeIv;

    @BindView(R.id.bottom_ll)
    LinearLayout mBottomLl;
    @BindView(R.id.cancel_order_tv)
    TextView mCancelOrderTv;
    @BindView(R.id.reserve_again_tv)
    TextView mReserveAgainTv;


    @BindView(R.id.targetView)
    LinearLayout mTargetViewLl;

    private AppointmentServeListEntity.ListEntity mEntity;


    @Override
    protected void getBundleExtras(Bundle extras) {
        mEntity = (AppointmentServeListEntity.ListEntity) extras.getSerializable("entity");
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.act_order_details;
    }

    @Override
    protected View getLoadingTargetView() {
        return mTargetViewLl;
    }

    @Override
    protected void initViewsAndEvents() {

        StatusBarUtil.setStatusBarColor(this, R.color.color_FFB024);
        StatusBarUtil.StatusBarLightMode(this);
        //动态设置沉浸式状态栏的高度
        CustomUtils.setImmersiveStatusBar(mContext, mTargetViewLl);
        //初始化view
        initView();
    }

    private void initView() {
        mStoreNameTv.setText(mEntity.getName());
        mStoreAddressTv.setText(mEntity.getAddress());
        mOrderTimeTv.setText(mEntity.getAppointmentTime());
        mServiceNameTv.setText(mEntity.getServiceName());
        mTechnicianNameTv.setText(mEntity.getTechnicianName());
        mOrderNumberTv.setText(mEntity.getOrderCode());

        if (!StringUtil.isEmpty(mEntity.getUserPhone())) {
            mPhoneNumberTv.setText(mEntity.getUserPhone().replaceAll("(?<=\\d{3})\\d" + "(?=\\d{4})", "*"));
        }

        mOrderCreateTimeTv.setText(mEntity.getCreateTime());

        switch (mEntity.getStatus()) {
            case 0:
                mOrderStatusTv.setText("预约成功");
                mOrderStatusIv.setImageResource(R.mipmap.appointment_success_tag);
                mQrCodeLl.setVisibility(View.VISIBLE);
                mOrderDescriptionTv.setText("请您按时到店接受服务，行程有变请及时取消。");

                mBottomLl.setVisibility(View.VISIBLE);
                mCancelOrderTv.setVisibility(View.VISIBLE);
                mReserveAgainTv.setVisibility(View.GONE);
                break;
            case 1:
                mOrderStatusTv.setText("进行中");
                mQrCodeLl.setVisibility(View.GONE);
                mOrderStatusIv.setImageResource(R.mipmap.appointment_underway_tag);
                mOrderDescriptionTv.setText("商家正在为您进行优质服务。");

                mBottomLl.setVisibility(View.GONE);
                break;
            case 2:
                mOrderStatusTv.setText("订单已完成");
                mOrderStatusIv.setImageResource(R.mipmap.appointment_success_tag);
                mQrCodeLl.setVisibility(View.GONE);
                mOrderDescriptionTv.setText("这单已经完成了，您可以选择再次预约。");

                mBottomLl.setVisibility(View.VISIBLE);
                mCancelOrderTv.setVisibility(View.GONE);
                mReserveAgainTv.setVisibility(View.VISIBLE);
                break;
            case 3:
                mOrderStatusTv.setText("预约已取消");
                mOrderStatusIv.setImageResource(R.mipmap.appointment_cancel_tag);
                mQrCodeLl.setVisibility(View.GONE);
                mOrderDescriptionTv.setText("已为您取消本次预约");

                mBottomLl.setVisibility(View.VISIBLE);
                mCancelOrderTv.setVisibility(View.GONE);
                mReserveAgainTv.setVisibility(View.VISIBLE);
                break;
        }
        //根据订单生成二维码
        try {
            Bitmap qrCode = createQRCode(mEntity.getOrderCode2());
            mQrCodeIv.setImageBitmap(qrCode);
        } catch (WriterException e) {
            e.printStackTrace();
        }

    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return false;
    }

    @Override
    protected boolean isBindEventBusHere() {
        return false;
    }

    @Override
    protected boolean toggleOverridePendingTransition() {
        return false;
    }

    @Override
    protected TransitionMode getOverridePendingTransitionMode() {
        return null;
    }

    @Override
    protected boolean isApplyKitKatTranslucency() {
        return false;
    }

    @Override
    public void showBusinessError(ErrorBean error) {

    }

    @OnClick({R.id.back_iv, R.id.cancel_order_tv, R.id.reserve_again_tv, R.id.store_phone_iv, R.id.store_name_tv})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back_iv://返回键
                finish();
                break;
            case R.id.cancel_order_tv:
                Intent intent = new Intent(this, ACT_CancelAppointment.class);
                Bundle bundle = new Bundle();
                bundle.putString("id", mEntity.getId());
                bundle.putString("orderCode", mEntity.getOrderCode());
                intent.putExtras(bundle);
                startActivityForResult(intent, 1);
                break;
            case R.id.reserve_again_tv:
                Bundle b = new Bundle();
                b.putString("orderId", mEntity.getId());
                b.putString("shopId", mEntity.getShopId());
                b.putString("storePhone", mEntity.getFixPhone());
                readyGo(ACT_ShopAppointment.class, b);
                break;
            case R.id.store_phone_iv:
                CustomUtils.setCallPhoneDialog(this, mEntity.getFixPhone());
                break;
            case R.id.store_name_tv:
                readyGo(ACT_ShopDetail.class, new Intent().putExtra("id", mEntity.getShopId()));
                break;
        }
    }

    /**
     * 2      * 生成QRCode（二维码）
     * 3      *
     * 4      * @param str
     * 5      * @return
     * 6      * @throws WriterException
     * 7
     */
    public static Bitmap createQRCode(String url) throws WriterException {
        if (url == null || url.equals("")) {
            return null;
        }

        // 生成二维矩阵,编码时指定大小,不要生成了图片以后再进行缩放,这样会模糊导致识别失败
        BitMatrix matrix = new MultiFormatWriter().encode(url,
                BarcodeFormat.QR_CODE, 300, 300);

        int width = matrix.getWidth();
        int height = matrix.getHeight();

        // 二维矩阵转为一维像素数组,也就是一直横着排了
        int[] pixels = new int[width * height];

        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                if (matrix.get(x, y)) {
                    pixels[y * width + x] = 0xff000000;
                }
            }
        }

        Bitmap bitmap = Bitmap.createBitmap(width, height,
                Bitmap.Config.ARGB_8888);
        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
        return bitmap;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mEntity.setStatus(data.getIntExtra("orderStatus", 0));
        initView();
    }
}
